/**
 * 商品批量导入页面
 */
import React, { useState, useRef } from 'react';
import { Button, Modal, message } from 'antd';
import axios from 'axios';
import { useTranslation } from '@/utils/i18n';

interface ErrorItem {
  row: number;
  error: string;
  data: Record<string, string>;
}

interface UploadProgress {
  filename: string;
  progress: number;
  status: 'uploading' | 'success' | 'error';
  message?: string;
}

const ProductUpload: React.FC = () => {
  const { t } = useTranslation();
  const [uploadProgressList, setUploadProgressList] = useState<UploadProgress[]>([]);
  const [batchAddResult, setBatchAddResult] = useState<{
    visible: boolean;
    total: number;
    success: number;
    failed: number;
    errors: ErrorItem[];
  }>({ visible: false, total: 0, success: 0, failed: 0, errors: [] });
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dragRef = useRef<HTMLDivElement>(null);
  
  // 更新上传进度
  const updateProgress = (
    filename: string, 
    progress: number, 
    status?: 'uploading' | 'success' | 'error',
    message?: string
  ) => {
    setUploadProgressList(prev => 
      prev.map(item => 
        item.filename === filename 
          ? { ...item, progress, status: status || item.status, message }
          : item
      )
    );
  };
  
  // 处理文件上传
  const handleFileUpload = async (fileList: FileList) => {
    const files = Array.from(fileList);
    
    for (const file of files) {
      const progressItem: UploadProgress = {
        filename: file.name,
        progress: 0,
        status: 'uploading'
      };
      setUploadProgressList(prev => [...prev, progressItem]);

      try {
        // 浏览器兼容的文件扩展名获取方法
        const getFileExtension = (filename: string): string => {
          const lastDotIndex = filename.lastIndexOf('.');
          return lastDotIndex >= 0 ? filename.slice(lastDotIndex).toLowerCase() : '';
        };
        
        // 只支持.xlsx和.xls格式
        const fileExt = getFileExtension(file.name);
        if (fileExt !== '.xlsx' && fileExt !== '.xls') {
          message.error(`${file.name} 不是支持的文件格式，请选择Excel文件(.xlsx, .xls)格式！`);
          updateProgress(file.name, 0, 'error', '不支持的文件格式');
          continue;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('updateExisting', 'false');
        formData.append('skipValidation', 'false');
        
        // 调用批量导入接口
        const response = await axios.post('http://localhost:3000/hsl/product/batch/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
            updateProgress(file.name, percentCompleted);
          }
        });
        
        updateProgress(file.name, 100, 'success', '上传成功');
        
        const responseData = response.data;
        
        if (responseData.code === 200) {
          // 成功情况
          const resultData = responseData.data || {};
          const errors: ErrorItem[] = [];
          if (resultData.errors && Array.isArray(resultData.errors)) {
            resultData.errors.forEach((err: { row: number; errors?: string[]; error?: string; data?: Record<string, unknown> }) => {
              const errorMessages = err.errors ? err.errors.join(', ') : err.error || '数据验证失败';
              errors.push({
                row: err.row,
                error: errorMessages,
                data: err.data ? Object.fromEntries(
                  Object.entries(err.data).map(([k, v]) => [k, String(v)])
                ) : {}
              });
            });
          }
          
          setBatchAddResult({
            visible: true,
            total: resultData.totalRows || 0,
            success: resultData.successRows || 0,
            failed: resultData.failedRows || 0,
            errors: errors
          });
          message.success(responseData.msg || '商品数据批量添加成功');
        } else {
          // 失败情况
          message.error(responseData.msg || '批量添加失败');
          const errors: ErrorItem[] = [];
          if (responseData.data?.errors && Array.isArray(responseData.data.errors)) {
            responseData.data.errors.forEach((err: { row?: number; errors?: string[]; error?: string; data?: Record<string, unknown> }) => {
              const errorMessages = err.errors ? err.errors.join(', ') : err.error || '数据验证失败';
              errors.push({
                row: err.row || 0,
                error: errorMessages,
                data: err.data ? Object.fromEntries(
                  Object.entries(err.data).map(([k, v]) => [k, String(v)])
                ) : {}
              });
            });
          } else {
            errors.push({ row: 0, error: responseData.msg || '批量添加失败', data: {} });
          }
          
          setBatchAddResult({
            visible: true,
            total: responseData.data?.totalRows || 0,
            success: responseData.data?.successRows || 0,
            failed: responseData.data?.failedRows || 0,
            errors: errors
          });
        }
      } catch (error) {
        console.error('批量添加失败:', error);
        const errorMessage = error instanceof Error 
          ? error.message 
          : '批量添加失败，请检查网络连接或文件格式';
        message.error(errorMessage);
        updateProgress(file.name, 0, 'error', errorMessage);
        
        setBatchAddResult({
          visible: true,
          total: 0,
          success: 0,
          failed: 0,
          errors: [{ row: 0, error: errorMessage, data: {} }]
        });
      }
    }
  };
  
  // 文件拖拽上传处理
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileUpload(files);
    }
  };
  
  // 关闭批量添加结果弹窗
  const handleCloseBatchResult = () => {
    setBatchAddResult(prev => ({ ...prev, visible: false }));
  };
  
  // 下载批量添加模板
  const handleDownloadTemplate = async () => {
    try {
      // 首先尝试调用后端的模板生成接口
      const response = await axios.get('http://localhost:3000/hsl/product/import/template');
      if (response.data && response.data.fileUrl) {
        // 如果后端返回了文件URL，直接下载
        const link = document.createElement('a');
        link.href = response.data.fileUrl;
        link.download = '商品批量添加模板.xlsx';
        link.click();
        message.success('模板下载成功，请按照模板格式填写数据');
        return;
      }
    } catch (error) {
      console.log('调用后端模板接口失败，使用本地生成的模板:', error);
    }
    
    // 本地回退方案 - 创建模板
    const headers = ['商品名称', '商店名称', '商品信息', '价格', '库存', '类型'];
    const sampleData = [
      ['测试商品1', '测试店铺A', '这是一个测试商品的详细描述', '99.99', '1', ''],  // nums最小值为1
      ['测试商品2', '测试店铺B', '另一个测试商品的详细描述', '199.50', '2', '']
    ];
    
    // 生成CSV内容（包含BOM以支持Excel正确识别中文）
    const rows = [
      ['商品批量添加模板说明：'],
      ['重要：请使用Excel软件打开此模板，填写完成后保存为.xlsx或.xls格式上传'],
      ['商品名称：必填'],
      ['商店名称：必填'],
      ['商品信息：可选'],
      ['价格：必填，数字格式'],
      ['库存：必填，数字格式，最小值为1'],
      ['类型：可选，可以填写类型名称或ID'],
      [''], // 空行
      headers, // 表头
      ...sampleData // 示例数据
    ];
    const csvContent = rows.map(row => row.join(',')).join('\n');
    
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '商品批量添加模板.csv';
    link.click();
    
    message.success('模板下载成功，请使用Excel软件打开并保存为.xlsx或.xls格式后上传');
  };

  return (
    <div className="min-h-screen space-y-6 p-6 bg-gray-50 dark:bg-slate-950 transition-colors">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">{t('product.upload.title') || '商品批量导入'}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">{t('product.upload.subtitle') || '通过Excel文件批量导入商品数据'}</p>
      </div>

      <div className="bg-white dark:bg-slate-900/80 border border-transparent dark:border-slate-800 rounded-lg shadow p-6 transition-colors">
        <div className="space-y-4">
          <div className="text-gray-600 dark:text-slate-200">
            <h3 className="font-medium mb-2">批量添加说明：</h3>
            <ul className="list-disc pl-5 space-y-1">
              <li>请使用Excel文件(.xlsx, .xls)格式上传</li>
              <li>文件大小限制：10MB</li>
              <li>每行数据代表一个商品，支持批量导入多个商品</li>
              <li>请确保数据格式正确，特别是价格和库存必须为数字</li>
            </ul>
          </div>
          
          {/* 文件选择按钮 */}
          <div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept=".xlsx,.xls"
              className="hidden"
              onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2"
            >
              📤 选择Excel文件
            </button>
          </div>
          
          {/* 下载模板按钮 */}
          <div>
            <button
              onClick={handleDownloadTemplate}
              className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 flex items-center gap-2"
            >
              📄 下载批量模板
            </button>
          </div>
          
          {/* 拖拽上传区域 - 直接显示，不需要点击按钮 */}
          <div
            ref={dragRef}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
            className="border-2 border-dashed border-gray-300 dark:border-slate-700 rounded-lg p-8 text-center hover:border-blue-500 dark:hover:border-blue-400 transition-colors bg-gray-50 dark:bg-slate-900/60"
          >
            <div className="text-4xl mb-2">📁</div>
            <div className="text-gray-600 dark:text-slate-200">拖拽Excel文件到这里上传</div>
            <div className="text-sm text-gray-400 dark:text-slate-400 mt-1">支持.xlsx和.xls格式</div>
          </div>
          
          {/* 上传进度显示 */}
          {uploadProgressList.length > 0 && (
            <div className="mt-4">
              <h3 className="font-semibold mb-3">上传进度</h3>
              {uploadProgressList.map((item, index) => (
                <div key={index} className="mb-3">
                  <div className="flex justify-between text-sm mb-1">
                    <span className="dark:text-slate-200">{item.filename}</span>
                    <span className={
                      item.status === 'success' ? 'text-green-500' :
                      item.status === 'error' ? 'text-red-500' :
                      'text-blue-500'
                    }>
                      {item.status === 'success' ? '✓ ' : item.status === 'error' ? '✗ ' : ''}
                      {item.progress}%
                    </span>
                  </div>
                  <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                    <div
                      className={`h-2 rounded-full transition-all ${item.status === 'success' ? 'bg-green-500' : item.status === 'error' ? 'bg-red-500' : 'bg-blue-500'}`}
                      style={{ width: `${item.progress}%` }}
                    />
                  </div>
                  {item.message && (
                    <div className="text-xs text-gray-500 dark:text-slate-400 mt-1">{item.message}</div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
      
      {/* 批量添加结果弹窗 */}
      <Modal
        title="批量添加结果"
        open={batchAddResult.visible}
        onOk={handleCloseBatchResult}
        onCancel={handleCloseBatchResult}
        footer={[
          <Button key="close" onClick={handleCloseBatchResult}>
            关闭
          </Button>
        ]}
        width={600}
      >
        <div className="space-y-4">
          <div>
            <p><strong>总数据行数：</strong>{batchAddResult.total}</p>
            <p><strong>成功添加：</strong><span style={{ color: '#52c41a' }}>{batchAddResult.success}</span></p>
            <p><strong>添加失败：</strong><span style={{ color: batchAddResult.failed > 0 ? '#ff4d4f' : '#333' }}>{batchAddResult.failed}</span></p>
          </div>
          
          {batchAddResult.errors.length > 0 && (
            <div>
              <h4 style={{ color: '#ff4d4f', marginBottom: '12px' }}>错误信息：</h4>
              <div className="bg-gray-100 dark:bg-gray-700 p-4 rounded">
                {batchAddResult.errors.map((error, index) => (
                  <div key={index} className="mb-2">
                    {error.row > 0 && <span style={{ fontWeight: 'bold' }}>第{error.row}行：</span>}
                    {error.error}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}

export default ProductUpload

